package com.xcc;

import com.xcc.app.App;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient extends Thread {
    public TCPClient(Socket socket, App app) {
        this.socket = socket;
        this.app = app;
        app.connect(this);
    }

    private Socket socket;
    private App app;

    public Socket getSocket() {
        return socket;
    }

    public void run() {
        // 接收信息
        try {
            while (true) {
                String msg = "";
                InputStream inputStream = socket.getInputStream();

                // 1
                // byte[] bs = new byte[100];
                // BufferedInputStream in=new BufferedInputStream(inputStream);
                // for (int i = 0; (i = inputStream.read(bs)) > 0;) {
                // msg += new String(bs, 0, i);
                // }

                // 2
                // InputStreamReader in = new InputStreamReader(inputStream);
                // BufferedReader reader = new BufferedReader(in);
                // msg = reader.readLine();

                // int sendBufferSize = socket.getReceiveBufferSize();
                byte[] bs = new byte[100];
                int i = 0;
                while ((i = inputStream.read(bs)) > 0) {
                    msg += new String(bs, 0, i);
                    if (i < 100) {
                        break;
                    }
                }
                //inputStream.close();
                if (msg != null && msg.length() > 0)
                    app.acceptMsg(this, msg);
                else {
                    app.clientOut(this);
                    break;
                }
            }
        } catch (IOException e) {
            // e.printStackTrace();

            // 用户断开
            app.clientOut(this);
        }
    }

    public void sendMsg(String msg) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            // outputStream.write((msg + "\n").getBytes());
            outputStream.write(msg.getBytes());
            outputStream.flush();
            //outputStream.close();
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }

    public String getAddress() {
        return socket.getPort() + "" + socket.getInetAddress().getHostAddress();
    }
}
